package com.zzyl.oss.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(name = "file.storage.local.enabled", havingValue = "true", matchIfMissing = true)

public class LocalFileStorageService implements FileStorageService {

    @Value("${ruoyi.profile}")
    private String storagePath;

    @Value("${server.port:8080}")
    private String serverPort;

    @Override
    public String store(MultipartFile file, String fileName) {
        try {
            // 创建日期目录
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fileExtension = getFileExtension(fileName);
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            // 目标路径 - 使用配置的路径
            String relativePath = datePath + "/" + uniqueFileName;
            Path targetPath = Paths.get(storagePath, relativePath);

            // 确保目录存在
            Files.createDirectories(targetPath.getParent());

            // 保存文件
            Files.copy(file.getInputStream(), targetPath);

            log.info("本地文件上传成功: {}", relativePath);

            // 返回访问URL - 使用/uploadPath路径（与Security放行路径一致）
            String baseUrl = "http://localhost:" + serverPort;
            return baseUrl + "/uploadPath/" + relativePath;

        } catch (IOException e) {
            log.error("本地文件上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf(".");
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex) : "";
    }
}
